<?php

namespace App\Http\Controllers\Api;

use App\Address;
use App\Http\Requests\StoreAddress;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class AddressController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $addresses = Address::where('user_id', Auth::id())->orderBy('is_default', 'desc')->get();
        return $addresses;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * @param StoreAddress $request
     * @return mixed
     */
    public function store(StoreAddress $request)
    {

        $address = Address::create(array_merge($request->all(), ['user_id' => Auth::id()]));
        return $address;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Address  $address
     * @return \Illuminate\Http\Response
     */
    public function show(Address $address)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Address  $address
     * @return \Illuminate\Http\Response
     */
    public function edit(Address $address)
    {
        //
    }

    /**
     * @param StoreAddress $request
     * @param Address $address
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function update(StoreAddress $request, Address $address)
    {
        $address->update($request->all());
        return $address;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Address  $address
     * @return \Illuminate\Http\Response
     */
    public function destroy(Address $address)
    {
        $address->delete();
        return response(['message' => '删除成功']);
    }

    public function setDefault(Address $address)
    {
        $default = $address->is_default;
        Address::where('user_id', Auth::id())->update(['is_default' => 0]);
        $address->is_default = !$default;
        $address->save();
        return response(['message' => '修改成功']);
    }
}
